import * as CryptoJS from 'crypto-js';

class CryptoUtil {
  secretKey: string;
  salt: string;
  constructor(secretKey: string, salt: string) {
    this.secretKey = secretKey; // 密钥，前后端共享
    this.salt = salt; // 盐值，前后端共享
  }

  // 将盐值和密钥结合，生成一个用于加密的密钥
  generateKey() {
    const key = CryptoJS.PBKDF2(this.secretKey, this.salt, {
      keySize: 256 / 32,
      iterations: 10000,
    });
    return key.toString(CryptoJS.enc.Hex);
  }

  // 加密文本
  encrypt(text: string) {
    const key = this.generateKey();
    const encrypted = CryptoJS.AES.encrypt(text, key);
    return encrypted.toString();
  }

  // 解密文本
  decrypt(encryptedText: string | CryptoJS.lib.CipherParams) {
    const key = this.generateKey();
    const decrypted = CryptoJS.AES.decrypt(encryptedText, key);
    return decrypted.toString(CryptoJS.enc.Utf8);
  }
}
export default CryptoUtil;
